﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MapReduce.Comm
{
    public class JobManagerUtil<T>
    {
        private String mServiceName;
        private IJob<T> mJob = null;
        private ushort mPort;

        public JobManagerUtil(String pServiceName, IJob<T> pJob, ushort pPort)
        {
            mServiceName = pServiceName; 
            mJob = pJob;
            mPort = pPort;
            
        }
 
        public byte[][] GetIpArray(List<KeyValuePair<String, T>> pChunkInput)
        {
            //Create an input for job service.
            List<byte[]> list2D = new List<byte[]>();
            list2D.Add(SerializeAssembly(mJob));
            list2D.Add(SerializeAssemblyName(mJob));
            list2D.Add(SerializeClassName(mJob));


            //Copy chunk input in local variable. This is needed so that we can use it in
            //delegate.
            //List<KeyValuePair<String, T>> localChunkInput =  new List<KeyValuePair<string, T>>();


            foreach (KeyValuePair<String, T> pair in pChunkInput)
            {
                list2D.Add(U.GetBytes(pair.Key));
                list2D.Add(U.GetBytes(pair.Value));

                //store in a local copy too
                //localChunkInput.Add(new KeyValuePair<String, T>(pair.Key, pair.Value));
            }

            return list2D.ToArray();
        }//foo

        private static byte[] SerializeClassName(Object pO)
        {
            return U.GetBytes(pO.GetType().FullName);
        }
        private static byte[] SerializeAssembly(IJob<T> pO)
        {
            //return pO.GetType().Assembly.
            return File.ReadAllBytes(pO.GetType().Assembly.Location);
        }
        private static byte[] SerializeAssemblyName(IJob<T> pO)
        {
            //return pO.GetType().Assembly.
            return U.GetBytes(pO.GetType().Assembly.ManifestModule.Name);
        }
    }
}
